

package yf.mall.service.impl.app;

import com.yf.utils.DateUtil;
import org.apache.commons.lang.time.DateUtils;
import org.checkerframework.checker.units.qual.K;
import org.springframework.transaction.annotation.Transactional;
import yf.mall.component.helper.OrderHelper;
import yf.mall.entity.KolOrderEntity;
import yf.mall.entity.KolOrderEntityExample;
import yf.mall.entity.custom.KolOrderStatMap;
import yf.mall.mapper.KolOrderExtMapper;
import yf.mall.utils.app.AppUtil;
import yf.mall.vo.up.KolOrderStatUp;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.excel.context.AnalysisContext;

import java.io.InputStream;

import com.alibaba.excel.event.AnalysisEventListener;
import org.springframework.stereotype.Service;
import com.alibaba.excel.EasyExcel;
import yf.mall.vo.down.KolOrderStatDown;

import java.math.BigDecimal;
import java.util.*;
import java.net.URLEncoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;

import yf.mall.dao.KolOrderStatDao;
import yf.mall.entity.KolOrderStatEntity;
import yf.mall.vo.KolOrderStatVo;
import yf.mall.service.app.KolOrderStatService;
import com.yf.service.impl.BaseServiceImpl;

/**
 * 账户记录Service实现类
 *
 * 
 * 
 * @date Sun Jul 30 10:43:48 CST 2023
 */
@Service
public class KolOrderStatServiceImpl extends BaseServiceImpl<KolOrderStatEntity> implements KolOrderStatService {

    private KolOrderStatDao dao;

    @Resource
    private KolOrderExtMapper kolOrderExtMapper;


    @Autowired
    public void setDao(KolOrderStatDao dao) {
        this.dao = dao;
        super.setBaseDao(dao);
    }


    @Override
    public List<KolOrderStatVo> findVo(KolOrderStatVo vo) {
        return dao.findVo(vo);
    }

    @Override
    public KolOrderStatVo getVo(Long id) {
        return dao.getVo(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveVo(KolOrderStatVo vo) {
        return dao.save(vo.getEntity());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateVo(KolOrderStatVo vo) {
        return dao.update(vo.getEntity());
    }


    @Override
    public void downLoad(HttpServletResponse response, List<KolOrderStatVo> list) {
        try {
            List<KolOrderStatDown> datas = list.stream().map(item -> new KolOrderStatDown(item)).collect(Collectors.toList());
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), KolOrderStatDown.class).sheet("模板").doWrite(datas);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Override
    public void upload(InputStream file) {
        EasyExcel.read(file, KolOrderStatUp.class, new UploadDataListener()).sheet().doRead();
    }


    class UploadDataListener extends AnalysisEventListener<KolOrderStatUp> {


        @Override
        @Transactional(rollbackFor = Exception.class)
        public void invoke(KolOrderStatUp upVo, AnalysisContext analysisContext) {
            saveVo(upVo.toVo());
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        }

    }


    /**内部方法**/


    /**
     * 外部方法实现
     **/
    @Override
    public List<KolOrderStatEntity> findOrderStatByOpenIds(List<String> openIds, Integer begin, Integer end, String orderBy, Integer limit) {
        if (limit == null) {
            limit = 10;
        }
        return dao.findOrderStatByOpenIds(openIds, begin, end, orderBy, limit);
    }

    @Override
    public KolOrderStatEntity calOrderStatByOrder(String openId, Date date) {
        Date begin = DateUtils.truncate(date, Calendar.DAY_OF_MONTH);
        Date end = DateUtils.addSeconds(DateUtils.addDays(date, 1), -1);
        KolOrderEntityExample orderExample = new KolOrderEntityExample();
        orderExample.createCriteria().andAuthorOpenidEqualTo(openId).andPaySuccessTimeBetween(begin, end);
        List<KolOrderEntity> orderEntityList = kolOrderExtMapper.selectByExample(orderExample);

        KolOrderStatEntity kolOrderStatEntity = OrderHelper.convertOrderToStatEntity(orderEntityList);
        if (kolOrderStatEntity == null) {
            return null;
        }
        kolOrderStatEntity.setOpenId(openId);
        kolOrderStatEntity.setDate(AppUtil.getIntegerDate(begin));
        return kolOrderStatEntity;
    }

    @Override
    public List<KolOrderStatEntity> calOrderStatByOrderWithRange(String openId, Date begin, Date end) {
        KolOrderEntityExample orderExample = new KolOrderEntityExample();
        orderExample.createCriteria().andAuthorOpenidEqualTo(openId).andPaySuccessTimeBetween(begin, end);
        List<KolOrderEntity> orderEntityList = kolOrderExtMapper.selectByExample(orderExample);

        Map<Date, List<KolOrderEntity>> orderMapByDate = orderEntityList.stream().collect(Collectors.groupingBy(
                o -> org.apache.commons.lang3.time.DateUtils.truncate(o.getPaySuccessTime(), Calendar.DAY_OF_MONTH),
                LinkedHashMap::new,
                Collectors.toList()
        ));
        List<KolOrderStatEntity> kolOrderStatEntities = new ArrayList<>();
        orderMapByDate.entrySet().forEach(entry -> {
            KolOrderStatEntity kolOrderStatEntity = OrderHelper.convertOrderToStatEntity(entry.getValue());
            if (kolOrderStatEntity == null) {
                return;
            }
            kolOrderStatEntity.setOpenId(openId);
            kolOrderStatEntity.setDate(AppUtil.getIntegerDate(entry.getKey()));
            kolOrderStatEntities.add(kolOrderStatEntity);
        });
        return kolOrderStatEntities;
    }

    @Override
    public List<KolOrderStatMap> findTopPayAmountOrderStat(Integer begin, Integer end, Integer limit) {
        return dao.findTopPayAmountOrderStat(begin, end, limit);
    }


}
